import os
import requests
import re
from tqdm import tqdm
import zipfile


ac_id =input('请输入你要下载的视频ID:')

url = f'https://www.acfun.cn/v/{ac_id}'

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36'
}
resp = requests.get(url, headers=headers)
#print(resp.text)

title = re.findall('<span>(.*?)</span>',resp.text)[0]
print(title)

m3u8_url = re.findall('backupUrl(.*?)\"]',resp.text)[0].replace('"', '').split('\\')[2]
#print(m3u8_url)
m3u8_data =requests.get(url=m3u8_url,headers=headers).text

m3u8_data = re.sub('#EXTM3U', '',m3u8_data)
m3u8_data = re.sub('#EXT-X-VERSION:\d', '',m3u8_data)
m3u8_data = re.sub('#EXT-X-TARGETDURATION:\d+', '',m3u8_data)
m3u8_data = re.sub('#EXT-X-MEDIA-SEQUENCE:\d', '',m3u8_data)
m3u8_data = re.sub('#EXTINF:\d\.\d+,', '',m3u8_data)
m3u8_data =re.sub('#EXT-X-ENDLIST', '',m3u8_data)
#print(m3u8_data)

m3u8_data_list = m3u8_data.split()
print(m3u8_data_list)

filename = f'{title}\\'
if not os.path.exists(filename):
    os.mkdir(filename)

print('正在开始下载ts文件，请稍后......')

pre_url = 'https://tx-safety-video.acfun.cn/mediacloud/acfun/acfun_video/'
files = os.listdir(filename)
if len(files) == 0:
    for item in m3u8_data_list:
        link_url =pre_url + item
        link_name =item.split('.')[1]
        link_content = requests.get(url=link_url,headers=headers).content

        with open(filename + link_name + '.ts', mode='wb')as f:
            f.write(link_content)

print('ts 视频下载完成!!!!!')

print('开始视频片段合成..............')
file =os.listdir(filename)
with zipfile.ZipFile(filename + title + 'mp4', mode='w')as z:
    for file in tqdm(files):
        ts_content = filename +file
        z.write(ts_content)
        os.remove(ts_content)

print('视频片段合并完成！！！！！！！！！')